﻿using ConfigurationServer.AppCode.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Serialization;

namespace ConfigurationServer.AppCode.Modules
{
    public class TimingModule : IHttpModule
    {
        private const bool blnLogInBD = true;
        private const bool blnLogEchoInPage = false; // WARNING Setting this echo in true will crash json action results for clients

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnBeginRequest;
            context.EndRequest += OnEndRequest;
        }

        void OnBeginRequest(object sender, System.EventArgs e)
        {
            if (HttpContext.Current.IsDebuggingEnabled)
            {
                CTimeTrack tmTrack = new CTimeTrack(); // this request track
                HttpContext.Current.Items["tmTrack"] = tmTrack;
                tmTrack.timeTrack("OnBeginRequest");
            }
        }

        void OnEndRequest(object sender, System.EventArgs e)
        {
            if (HttpContext.Current.IsDebuggingEnabled)
            {
                CTimeTrack tmTrack = (CTimeTrack)HttpContext.Current.Items["tmTrack"];
                tmTrack.timeTrack("OnEndRequest");

                if (blnLogInBD)
                    tmTrack.saveAsync(HttpContext.Current.Request.Path, tmTrack);

                if (blnLogEchoInPage)
                {
                    //controller =
                    StringBuilder strImpresion = new StringBuilder("<TABLE><TR><TD>DETALLE DE TIME TRACKING</TD></TR>");
                    foreach (string tmTrk in tmTrack.tracks.Keys)
                    {
                        strImpresion.Append("<TR><TD>");
                        strImpresion.Append(tmTrk);
                        strImpresion.Append(":");
                        strImpresion.Append(tmTrack.tracks[tmTrk].ToString());
                        strImpresion.Append("</TD></TR>");
                    }
                    strImpresion.Append("</TABLE>");
                    HttpContext.Current.Response.Write(strImpresion.ToString());
                }
            }
        }


    }
}